//app.js
App({
  onLaunch: function () {
    
    if (!wx.cloud) {
      // console.error('请使用 2.2.3 或以上的基础库以使用云能力')
    } else {
      wx.cloud.init({
        // env 参数说明：
        //   env 参数决定接下来小程序发起的云开发调用（wx.cloud.xxx）会默认请求到哪个云环境的资源
        //   此处请填入环境 ID, 环境 ID 可打开云控制台查看
        //   如不填则使用默认环境（第一个创建的环境）
        // env: 'my-env-id',
        traceUser: true,
      })
    }

    // this.globalData = {}
  },
  globalData:{

      preMusicId:'',
      pause:'',
      bgMusic:wx.getBackgroundAudioManager(),
      //获取随机数
      randomString:function (len) {

        　　var len = len || 32;
        　　var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';    /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
          　 var maxPos = chars.length;
        　　var pwd = '';
        　　for (var i = 0; i < len; i++) {
        　　　　pwd += chars.charAt(Math.floor(Math.random() * maxPos));
        　　}
        　　return pwd;
          
      },
      //获取当前播放信息【音频链接、图片等信息】
      getNowMusicInfo:function(fun){

        var self = this;

        var nowMusicId = JSON.parse(wx.getStorageSync('nowMusicId'))

        var list = JSON.parse(wx.getStorageSync(nowMusicId.uid)).programs

        var tabId = nowMusicId.tabid

        var id = nowMusicId.id

        var title =nowMusicId.name

        var uid = nowMusicId.uid

        for(var i = 0 ; i < list.length ; i++){

          if(list[i].id == nowMusicId.id){

            switch(tabId){

              case 0:

                wx.request({
                    
                  url:'https://api.imjad.cn/cloudmusic/',
                  data:{type:'dj',id:id},
                  method:'GET',
                  success(res){
                    
                    var musicUrl = res.data.data[0].url

                    var coverUrl = list[i].coverUrl


                    fun({musicUrl:musicUrl,coverUrl:coverUrl,title:title,tabid:tabId})
        
                  }
        
                })
              
              break;
              case 1:

                var sing = self.randomString(32)

                var timestamp = new Date().getTime()


                switch(uid){

                  case '0':

                    var musicUrl = 'https://6a69-jiangli-u21is-1302255938.tcb.qcloud.la/audio/fulu/' + id + '.mp3'

                    var coverUrl = 'https://6a69-jiangli-u21is-1302255938.tcb.qcloud.la/' + id + '.jpg?sign=' + sing + '&t=' +timestamp

                  break;
                  case '4':

                    var musicUrl = 'https://6a69-jiangli-u21is-1302255938.tcb.qcloud.la/audio/少儿赞美/2020/' + id + '.mp3'

                    var coverUrl = 'https://6a69-jiangli-u21is-1302255938.tcb.qcloud.la/gepu/sezm/2020/' + id + '.jpg?sign=' + sing + '&t=' +timestamp

                  break;
                  default:

                    var musicUrl = 'https://6a69-jiangli-u21is-1302255938.tcb.qcloud.la/' + id + '.mp3'

                    var coverUrl = 'https://6a69-jiangli-u21is-1302255938.tcb.qcloud.la/' + id + '.jpg?sign=' + sing + '&t=' +timestamp
                  
                  break;
                }


                fun({musicUrl:musicUrl,coverUrl:coverUrl,title:title,tabid:tabId})


              break;

              case 2:

                // console.log('这是要获取信息音频信息')

                var sing = self.randomString(32)

                var timestamp = new Date().getTime()

                var musicUrl = 'https://7a68-zhaohuaishuai-9bmq3-1301260178.tcb.qcloud.la/' + id + '.mp3'

                var coverUrl = 'https://7a68-zhaohuaishuai-9bmq3-1301260178.tcb.qcloud.la/' + id + '.jpg' 

                fun({musicUrl:musicUrl,coverUrl:coverUrl,title:title,tabid:tabId})

              break;
            }


            break;
          }
        }

      },
      //历史播放记录的ID缓存
      lishiMusic:function(){

        wx.getStorage({

          key: 'nowMusicId',

          success:function(res){

              var nowMusicId = JSON.parse(res.data)

              wx.getStorage({

                key: 'liShiJiLu',
                success:function(res){

                  var liShiJiLudata = JSON.parse(res.data)['programs']

                  wx.getStorage({

                    key: 'uid',
                    success:function(res){

                      for(var i = 0 ; i< liShiJiLudata.length; i++){

                        var oldId = liShiJiLudata[i]['id']

                        if(oldId == nowMusicId.id){
                          return
                        }

                      }


                      liShiJiLudata.push(nowMusicId)

                      wx.setStorageSync('liShiJiLu',JSON.stringify({programs:liShiJiLudata,count:liShiJiLudata.length}))


                    }
                  })

                },
                fail:function(res){

                  wx.getStorage({
                    key: 'uid',
                    success:function(res){

                      var arr = {programs:[],count:1}

                      var data = JSON.parse(res.data)

                      arr['programs'][0] = nowMusicId


                      wx.setStorageSync('liShiJiLu',JSON.stringify(arr))


                    }
                  })


                },

              })


          },
        })

      },
      //显示歌谱
      gepuHidde:function(e){

        if(e == undefined){
          var id = JSON.parse(wx.getStorageSync('nowMusicId')).id
        }else{
          var id = e.currentTarget.dataset.id
        }


        switch(JSON.parse(wx.getStorageSync('uid')).uid){

          case "4":

            var guPuUrl = 'https://6a69-jiangli-u21is-1302255938.tcb.qcloud.la/gepu/sezm/2020/' + id + '.jpg'

          break;
          default:
            var guPuUrl = 'https://6a69-jiangli-u21is-1302255938.tcb.qcloud.la/' + id + '.jpg'
           
          break;
        }


        wx.previewImage({
          urls: [guPuUrl],
          current:0,
          
        })

      },
       //补零
      PrefixInteger:function(num, n) {

        return (Array(n).join(0) + num).slice(-n);

      },
      //将秒转换成hh:mm:ss时间格式
      dateForma:function(num) {

        var m = num / 60
      
        if( Math.floor(m) > 0){

          var h = m / 60 

          var hh = this.PrefixInteger(Math.floor(h),2)

          var mm = this.PrefixInteger(Math.floor(((h - Math.floor(h)) * 60) / 60),2)

          var ss =  this.PrefixInteger(Math.floor(((h - Math.floor(h)) * 60 - mm) * 60),2)

          if(Math.floor(h) > 0){



            var result = hh+':' + mm + ':' + ss


          }else{

            var s = Math.floor( (m - Math.floor(m)) * 60 )

            var result = '00:' + this.PrefixInteger(Math.floor(m),2) + ':' +  this.PrefixInteger(s,2)

          }


        }else{

          if(Math.floor(num) < 10){

            var str = '0'

          }

          var result = '00:00:' + this.PrefixInteger(Math.floor(num),2)

        }


        return result;


      },
      // 判断链接是否是和上一次一样，一样则播放，不一样则切换链接
      playURLIsOrNo:function(e){

        var nowMusicId = JSON.parse(wx.getStorageSync('nowMusicId'))

        var self =  this

        var bgMusic = this.bgMusic

        // 设置播放链接
        this.getNowMusicInfo(function(res){

          
          //检测本次的歌曲ID是否和上一次的一样

          if(bgMusic.src !==undefined){

            if(bgMusic.src !== ''){

              var preMi = self.preMusicId

              var nowMi =nowMusicId.id


            }

          }

         

          if( bgMusic.src == undefined || preMi !== nowMi){  //resMusicSrc !== regBgMusicSrc

            // console.log('链接不同')

            bgMusic.src= res.musicUrl
            bgMusic.title =res.title
            bgMusic.coverImgUrl=res.coverUrl

            self.preMusicId = nowMi


          }

        })

        bgMusic.play()

        nowMusicId['status'] = 1
  
        wx.setStorageSync('nowMusicId', JSON.stringify(nowMusicId))

        var playListStatus = wx.getStorageSync('playListStatus')

        if(typeof playListStatus == 'number'){

          this.setPlayListStatus(playListStatus)

        }else{

          wx.setStorageSync('playListStatus', 0)

          this.setPlayListStatus(0)

        }

      },
      //列表循环设置
      lieBiaoXunHuan:function(e){

        // // console.log(e)

        var status = e.currentTarget.dataset.status

        var bgMusic =  this.bgMusic

        //// console.log(status)

        var self =  this;

        var nowMusicId = JSON.parse(wx.getStorageSync('nowMusicId'))

        var uid = nowMusicId.uid

        var tabid = nowMusicId.tabid

        var programs = JSON.parse(wx.getStorageSync(uid))

        var list = programs.programs

        switch(tabid){

          case 1:

            switch(status){
              
              case 'next':

                for(var i = 0 ; i < list.length ; i++){

                  if(list[i].id == nowMusicId.id){

                    //// console.log('找到了相同的ID=》',nowMusicId.id)

                  // // console.log('找到了相同的ID=》',i)

                    //// console.log('当前列表的个数',list.length)
          
                    if(i + 1 > list.length){
                
                      var newMusicId = list[0]
          
                      break;
                      
                    }else{

                        //// console.log('进入到了小于当前数组的个数中')
        
                        if(list[i + 1].bz !==undefined){
        
                          var newMusicId = list[i + 1]
        
                          break;

        
                        }else{


                        // // console.log('进入到了下一首歌曲无法播放进行筛选的过程')

                          var nowIndex = i+1
        
        
                          for(var j = nowIndex ; j < list.length ; j++){
        
        
                              if(list[j].bz !== undefined){
          
                                var newMusicId = list[j]
        
                                break;
                              }
        
                          }

                          if(newMusicId == undefined){

                            if(list[0].bz !== undefined){

                              var newMusicId = list[0]

                            }else{

                              for(var j = 0 ; j < list.length ; j++){
                                if(list[j].bz !== undefined){
                                  var newMusicId = list[j]
                                  break;
                                }
                              }

                            }

                          
        
                            break;
                          }
        
                        }
          
                      
          
                    }
                  
        
                  }
        
                }
              
              break;

              case 'previous':

                for(var i = 0 ; i < list.length ; i++){


                  if(list[i].id == nowMusicId.id){
          
                    if(i - 1 == -1){
                
                      if(list[list.length -1].bz　!== undefined){

                        var newMusicId = list[list.length -1]

                        break;

                      }else{

                        for(j = list.length-1; j >= 0 ; j--){

                          if(list[j].bz !== undefined){
          
                            var newMusicId = list[j]

                            break;
                          }

                        }

                      }
          
                      break;
                      
                    }else{
        
                        if(list[i - 1].bz !==undefined){
        
                          var newMusicId = list[i - 1]
        
                          break;
        
                        }else{

        
                          var nowIndex = i - 1
        
                          for(var j = nowIndex ; j >= 0 ; j--){
        
        
                              if(list[j].bz !== undefined){
          
                                var newMusicId = list[j]
        
                                break;
                              }
        
                          }

                          
        
                        }
          
                      
          
                    }
                  
        
                  }
        
                }
              
              break;
              
              case 'random':

                var maxNum = list.length;

                var min = 0;

                var rand = Math.floor(Math.random() * maxNum - min + 1) + min

                var newMusicId = list[rand]


              break;
            
            }
          
          break;

          case 0:

          case 2:

            switch(status){

              case 'next':

                for(var i = 0 ; i < list.length ; i++){

                  if(list[i].id == nowMusicId.id){
            
                      if(i + 1 > list.length){
                
                        var newMusicId = list[0]
            
                        break;
                        
                      }else{
            
                          var newMusicId = list[i + 1]
            
                          break;
            
                      }
                  }
                }
              break;
              case 'previous':

                for(var i = 0 ; i < list.length ; i++){

                  if(list[i].id == nowMusicId.id){
            
                      if(i - 1 == -1){
                
                        var newMusicId = list[list.length - 1]
            
                        break;
                        
                      }else{
            
                        var newMusicId = list[i - 1]
          
                        break;
            
                      }
                  }
                }

              break;
              case 'random':

                var maxNum = list.length;

                var min = 0;

                var rand = Math.floor(Math.random() * maxNum - min + 1) + min

                var newMusicId = list[rand]

              break;
            }

          break;
        }

        

        var nowObj ={id:newMusicId.id,status:1,name:newMusicId.name,uid:nowMusicId.uid,tabid:nowMusicId.tabid}

        wx.setStorageSync('nowMusicId', JSON.stringify(nowObj))

        this.getNowMusicInfo(function(res){

          bgMusic.src= res.musicUrl
          bgMusic.title =res.title
          bgMusic.coverImgUrl=res.coverUrl

        })

        return nowObj

      },
      //设置播放状态 
      setPlayListStatus:function(playListStatus){

        var self  = this;

        var bgMusic = this.bgMusic;

        switch(playListStatus){

          case 0:

            // console.log('设置单曲循环播放')

            bgMusic.onEnded(function(){

              self.getNowMusicInfo(function(res){
        
                bgMusic.src= res.musicUrl
                bgMusic.title =res.title
                bgMusic.coverImgUrl=res.coverUrl
        
              })
        
            })

          break;

          case 1:


            // console.log('设置列表循环播放')

              bgMusic.onEnded(function(){
              //e.currentTarget.dataset.status 
              self.lieBiaoXunHuan({currentTarget:{dataset:{status:'next'}}})


            })

          break;

          case 2:

            // console.log('设置随机播放')

            bgMusic.onEnded(function(){

              
                self.lieBiaoXunHuan({currentTarget:{dataset:{status:'random'}}})
              

            })
            
          
          break;

          case 3:

            // console.log('设置单曲播放')

            bgMusic.onEnded(function(){

              
              var nowMusicId = JSON.parse(wx.getStorageSync('nowMusicId'))

              nowMusicId['status'] = 0

              wx.setStorageSync('nowMusicId', JSON.stringify(nowMusicId))


             })

          break;

        }
      },
      //获取动态播放列表
      getDongTaiLieBiao:function(){

        var nowMusicId = wx.getStorageSync('nowMusicId')

        if(nowMusicId !== ''){

          var boDanIs = JSON.parse(nowMusicId).boDanIs

          if(boDanIs){

            var uid = JSON.parse(nowMusicId).uid

            var tabid = JSON.parse(nowMusicId).tabid

            var bodanList = JSON.parse(wx.getStorageSync(uid))

            // console.log('nowUid=>',bodanList)


            for( var i = 0 ; i < bodanList.programs.length ; i++){

              bodanList.programs[i]['uid'] = uid

              bodanList.programs[i]['tabid'] = tabid
 
            }

          }else{

            var uid = JSON.parse(nowMusicId).uid

            var tabid = JSON.parse(nowMusicId).tabid

            var bodanList = JSON.parse(wx.getStorageSync(uid))

            if(tabid == 1){

              var pro = []

              for( var i = 0 ; i < bodanList.programs.length ; i++){

                if(bodanList.programs[i].bz !== undefined){

                  bodanList.programs[i]['uid'] = uid
                  bodanList.programs[i]['tabid'] = tabid
                  pro.push(bodanList.programs[i])
                }

              }

              bodanList = {programs:pro,count:pro.length,code:200,eore:true}

            }else{


              for( var i = 0 ; i < bodanList.programs.length ; i++){

                

                  bodanList.programs[i]['uid'] = uid

                  bodanList.programs[i]['tabid'] = tabid
              

              }

            }

          }



        }else{

          var bodanList = {programs:[],count:0}

        }

      


        

        
        var lishiJiLu = wx.getStorageSync('liShiJiLu')

        if(lishiJiLu == ''){

          var lishiJiLu = {programs:[],count:0}
        }else{

          var lishiJiLu = JSON.parse(wx.getStorageSync('liShiJiLu'))
        }

        var myBodan = wx.getStorageSync('boDan')

        if(myBodan == ''){
          
          var myBodan = {programs:[],count:0}

        }else{

          var myBodan = JSON.parse(wx.getStorageSync('boDan'))
        }

        var obj = {bodanList:bodanList,lishiJiLu:lishiJiLu,myBodan:myBodan}


        return obj

      },
      //动态列表点击歌名播放
      DongTaiPlay:function(e){

        var self = this ;
        var dataset = e.currentTarget.dataset

        dataset['status'] = 1

        wx.setStorageSync('nowMusicId', JSON.stringify(dataset))
        self.playURLIsOrNo()

        var uid = dataset.uid

       return this.getDongTaiLieBiao()


      },
      //动态列表显示与隐藏
      showListBoDan:function(status){

        var animation = wx.createAnimation({
          duration: 500,
          timingFunction: 'ease',
          delay: 0
         });

        switch(status){

          case 'show':
 
             animation.top(0).step()

          break;
          case 'hidden':

            animation.top('100%').step()

          break;
        }


        return animation


      },
      //设置当前列表播放状态按钮
      onPlayListStatus:function(){

        var playListStatus = wx.getStorageSync('playListStatus')

        var self = this

        if(typeof playListStatus !=='number'){

          wx.setStorageSync('playListStatus',0)

        }else{


          if(playListStatus > 1){

            playListStatus = -1

          }

          playListStatus = playListStatus + 1

          wx.setStorageSync('playListStatus', playListStatus)

        }

        this.setPlayListStatus(playListStatus)

        return playListStatus

      },
      onPause:function(fun){

        var bgMusic = this.bgMusic

        bgMusic.onPause(function(){

          var nowMusicId = wx.getStorageSync('nowMusicId')

          if(nowMusicId!==''){

            var nowMiObj = JSON.parse(nowMusicId)

            nowMiObj['status'] = 0

            wx.setStorageSync('nowMusicId', JSON.stringify(nowMiObj))

            fun()

          }
          

        })

      },
      onPlay:function(fun){

        var bgMusic = this.bgMusic

        bgMusic.onPlay(function(){

          var nowMusicId = wx.getStorageSync('nowMusicId')

          if(nowMusicId!==''){

            var nowObj = JSON.parse(nowMusicId)

            nowObj['status'] = 1

            wx.setStorageSync('nowMusicId', JSON.stringify(nowObj))

            fun()

          }

        })

      }

    


  },
 

})
